package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.db.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @auther : 白月尘
 * @date : 13:46  2021/10/28
 */
@Service
public class AnalysisService {
    @Autowired
    private LogMapper logMapper;//日志

    @Autowired
    private AnalysisMapper analysisMapper; //统计

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void analysis() throws ParseException {
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        //1、调用mapper根据要求查询数据
        //1.1 新注册用户数
        Integer logNum = logMapper.queryByTypeAndLogTime("0102", today);
        //1.2 活跃用户数
        Integer actNum = logMapper.queryByLogTime(today);
        //1.3 登陆次数
        Integer regNum = logMapper.queryByTypeAndLogTime("0101", today);
        //1.4 次日留存用户数
        Integer mumRetention1d = logMapper.queryMumRetention1d(today, yesterday);
        //2、根据日期查询统计数据
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(today);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("record_date",recordDate);
        Analysis analysis = analysisMapper.selectOne(queryWrapper);
        if (analysis==null){
            analysis = new Analysis();
            analysis.setNumRetention1d(mumRetention1d);
            analysis.setNumLogin(logNum);
            analysis.setNumRegistered(regNum);
            analysis.setNumActive(actNum);
            analysis.setRecordDate(recordDate);
            analysis.setCreated(new Date());
            analysisMapper.insert(analysis);
        }else {
            //2.2 数据存在的话，更新
            analysis.setNumRetention1d(mumRetention1d);
            analysis.setNumLogin(logNum);
            analysis.setNumRegistered(regNum);
            analysis.setNumActive(actNum);
            analysisMapper.updateById(analysis);
        }
    }

    public void deleteAnalysis() {
        String key = "deleteKey";
        //待删除的id
        String s = redisTemplate.opsForValue().get(key);
        String[] split = s.split(",");
        for (String s1 : split) {
            if (!s1.equals(",")) {
                try {
                    redisTemplate.delete(Constants.PEACH_BLOSSOM_KEY + s1);
                    redisTemplate.delete(Constants.PEACH_RECIVE_KEY + s1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
